const { series, parallel, src, dest, watch } = require('gulp')
const { js, libJs } = require('./gulpfile-js')
const config = require('./config.js')

const Path = require('path')

const htmlmin = require('gulp-htmlmin')
const fileinclude = require('gulp-file-include')
const changed = require('gulp-changed')
const webserver = require('gulp-webserver')
const del = require('del')
const uglify = require('gulp-uglify')
const plumber = require('gulp-plumber')
const cleanCss = require('gulp-clean-css')
const sass = require('gulp-sass')(require('sass'))
// const sass = require('gulp-sass')(require('node-sass')) // 如果是选择 node-sass 编译器，这样写
const imagemin = require('gulp-imagemin')
const cache = require('gulp-cache')
const webpack = require('webpack-stream')
const webpackConfig = require("./webpack.config.js")
const named = require('vinyl-named')
const preprocess = require("gulp-preprocess")
const sassVariables = require('gulp-sass-variables')


console.log('环境变量：' + process.env.NODE_ENV)

function html() {
  return src(['src/**/*.html', '!src/include/**.html'])
    .pipe(changed('dist'))
    .pipe(plumber())
    .pipe(fileinclude({
      prefix: '@@', //引用符号
      basepath: './src/include', //引用文件路径
    }))
    .pipe(preprocess({
      context: { ...config }
    }))
    .pipe(htmlmin({
      removeComments: true, //清除HTML注释
      collapseWhitespace: true, //压缩HTML
      collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
      removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
      removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
      removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
      minifyJS: true, //压缩页面JS
      minifyCSS: true //压缩页面CSS
    }))
    .pipe(dest('dist'))
}

// js 和 libJs 不再写在主配置上（下面虽然是注释掉，但可以认为已被删除），而是从 gulpfile-js.js 文件导入
// function js() {
//   return src(['src/js/**/*.js'])
//     .pipe(changed('dist/js/**/'))
//     .pipe(named(function (file) {
//       return file.relative.slice(0, -Path.extname(file.path).length)
//     }))
//     .pipe(webpack(webpackConfig))
//     .pipe(plumber())
//     .pipe(uglify())
//     .pipe(dest('dist/js'))
// }

// function libJs() {
//   return src(['src/lib/**/*.js'])
//     .pipe(changed('dist/lib/**/'))
//     .pipe(plumber())
//     .pipe(dest('dist/lib'))
// }

function css() {
  return src(['src/css/**/*.css'])
    .pipe(changed('dist/css/**/'))
    .pipe(plumber())
    .pipe(cleanCss())
    .pipe(dest('dist/css'))
}

function scss() {
  return src(['src/scss/**/*.scss'])
    .pipe(changed('dist/scss/**/'))
    .pipe(plumber())
    .pipe(sassVariables({
      $CDN: config.CDN,
    }))
    .pipe(sass())
    .pipe(cleanCss())
    .pipe(dest('dist/scss'))
}

function libCss() {
  return src(['src/libCss/**/*.css'])
    .pipe(changed('dist/libCss/**/'))
    .pipe(plumber())
    .pipe(dest('dist/libCss'))
}

// imagemin 7.x 版本的写法，注意：8.x 版本写法大改了
function img() {
  return src(['src/assets/img/**/*.{png,jpg,gif,jpeg,ico}']) //后缀都用小写，不然不识别
    .pipe(
      cache(
        imagemin({
        optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
        progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
        interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
        multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        })
      )
    )
    .pipe(dest('dist/assets/img'))
}

function devServer() {
  return src('dist').pipe(webserver({
    port: 3000,
    livereload: true, // 是否实时加载
    // directoryListing: true, // 是否开启浏览目录
    // open: true, // 是否自动打开
    // proxies: [ // 代理，可以用来解决跨域问题
    //   {source: '/api', target: 'http://xxxx.com', options: {headers: {"Content-Type": 'application/x-www-form-urlencoded'}}}
    // ]
  }))
}

function watcher() {
  watch('src/**/*.html', series(html)).on('unlink', function (path) {
    del('dist/**/' + Path.basename(path))
  })
  watch('src/js/**/*.js', series(js)).on('unlink', function (path) {
    del('dist/js/**/' + Path.basename(path))
  })
  watch('src/lib/**/*.js', series(libJs)).on('unlink', function (path) {
    del('dist/lib/**/' + Path.basename(path))
  })
  watch('src/css/**/*.css', series(css)).on('unlink', function (path) {
    del('dist/css/**/' + Path.basename(path))
  })
  watch('src/scss/**/*.scss', series(scss)).on('unlink', function (path) {
    var cssName = Path.basename(path).split('.scss')[0] // 请留意一下这里的代码
    del('dist/scss/**/' + cssName + '.css')
  })
  watch('src/libCss/**/*.css', series(libCss)).on('unlink', function (path) {
    del('dist/libCss/**/' + Path.basename(path))
  })
  watch('src/assets/img/**/*.{png,jpg,gif,jpeg,ico}', series(img)).on('unlink', function (path) {
    del('dist/assets/img/**/' + Path.basename(path))
  })
}

function clean() {
  return del('dist')
}

exports.default = series(clean, html, libJs, js, css, scss, libCss, img, devServer, watcher)
exports.build = series(clean, html, libJs, js, css, scss, libCss, img)
